package com.ezops.poc.validations.validators.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Utility class for doing type validation of Date field. Since the type
 * validation just call the valueOf method on the required type and tries to
 * convert string into the desired format.
 * <p>
 * 
 * Since {@link java.util.Date} doesn't have valueOf method and also the format
 * of date is also a decisive factor, use this class which decorate valueOf
 * method and tries to check if the given string is in desired format of date,
 * also if the date is a legitimate date or not.
 * 
 * @author vgaurav
 * 
 */
public class EzopsDateConverter implements ITypeConverter {

	private static final Logger logger = LoggerFactory
			.getLogger(EzopsDateConverter.class);
	private static List<String> knownDateFormats;

	private SimpleDateFormat dateFormat;
	
	private static final String defaultFormat = "yyyyMMdd";

	static {
		initKnowFormats();
	}

	private static void initKnowFormats() {
		// Vishal : We could have simply passed the format to SDF and , if it
		// throws exception then we know its not a correct format.But then user
		// should know the java date format, in case they decide to use some
		// other format, we can use a mapping technique here between user
		// defined format and java format.
		knownDateFormats = new ArrayList<>();
		knownDateFormats.add("yyyy-MM-dd");
		knownDateFormats.add("MM/dd/yyyy");
		knownDateFormats.add(defaultFormat);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ezops.poc.validations.validators.ITypeConverter#tryConvert(java.lang
	 * .String, java.lang.String)
	 */
	@Override
	public void tryConvert(String dateValue, String format)
			throws ConversionException, UnknownFormatException {
		logger.debug("Trying to convert {} to the format {}", dateValue, format);

		if(format == null || defaultFormat.equals("")){
			format = defaultFormat;
		}
		
		
		if (knownDateFormats.contains(format) == false) {
			throw new UnknownFormatException(format,
					"The format provided is not known to the converter");
		}
		dateFormat = new SimpleDateFormat(format);

		try {
			Date parsedDate = dateFormat.parse(dateValue);
			System.out.println(parsedDate);
		} catch (ParseException e) {

			logger.error(
					"Error while converting {} into {} format, Reason - [{}]",
					dateValue, format, e.getMessage());
			throw new ConversionException("Date", dateValue, e.getMessage());
		}

	}
}
